<?php
namespace app\index\model;

class Advert{
    //
    public static function instance(){
        return new Advert();
    }
    //
    public function get($path){
        $advert = $this->advert($path);
        if(!$advert){
            return null;
        }
        if($advert['pids']){
            $advert['pids'] = $this->product($advert['pids']);
        }
        $domain = $this->domain($advert['did']);
        if($domain){
            $advert['domain'] = $domain['domain'];
            $domain['baids'] = unserialize($domain['baids']);
            $advert['baids'] = array_unique(array_merge($advert['baids'], $domain['baids']));
            $domain['jscode'] = trim($domain['jscode']);
            if($domain['jscode']){
                $advert['jscode'] .= $domain['jscode'];
            }
        }
        unset($domain);
        if($advert['baids']){
            $advert['baids'] = $this->blockArea($advert['baids']);
        }
        $tnArr = $this->normalTpl($advert['tnid']);
        $advert['tnno'] = $tnArr['tnno'] ?? '';
        $advert['tnname'] = $tnArr['tname'] ?? '';
        unset($tnArr);
        $tbArr = $this->blockTpl($advert['tbid']);
        $advert['tbno'] = $tbArr['tbno'] ?? '';
        $advert['tbname'] = $tbArr['tname'] ?? '';
        unset($tbArr);
        return $advert;
    }
    //
    private function advert($path){
        $tmp = db('advert')->where('tname', '=', $path)->find();//null
        if($tmp){
            if($tmp['color']){
                $tmp['beian'] = '<span style="color:'.$tmp['color'].'">'.$tmp['beian'].'</span>';
            }
            $tmp['pids'] = unserialize($tmp['pids']);
            $tmp['baids'] = unserialize($tmp['baids']);
            $tmp['link'] = trim($tmp['link']);
            if($tmp['link']){
                if(strpos($tmp['link'], 'http://') === false && strpos($tmp['link'], 'https://') === false){
                    $tmp['link'] = 'http://'.$tmp['link'];
                }
            }
        }
        return $tmp;
    }
    //
    private function product($pidArr){
        $tmp = db('product')->where('pid', 'in', $pidArr)->field('pid,pname,price,oprice')->order('price asc')->select();//[]
        return $tmp;
    }
    //
    private function domain($did){
        $tmp = db('domain')->where('did', '=', $did)->field('domain,baids,jscode')->find();
        return $tmp;
    }
    //
    private function normalTpl($tnid){
        $tmp = db('tpl_normal')->where('tnid', '=', $tnid)->field('tname,tnno')->find();
        return $tmp;
    }
    //
    private function blockTpl($tbid){
        $tmp = db('tpl_block')->where('tbid', '=', $tbid)->field('tname,tbno')->find();
        return $tmp;
    }
    //
    private function blockArea($baidArr){
        $tmp = db('block_area')->where('baid', 'in', $baidArr)->column('area');//[]
        return $tmp;
    }
}